package com.xiaomaoguai.jsonp;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.gson.Gson;

/**
 * @Description :
 * @FileName: Jsonp1.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年5月12日 下午2:20:23
 * @Version:V1.00
 */
public class Jsonp1 {

	public static void main(String[] args) throws IOException {
		List<ProvinceCode> pList = new ArrayList<ProvinceCode>();
		Document document = Jsoup.connect("http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201504/t20150415_712722.html")
				.get();
		Elements tagP = document.select(".TRS_PreAppend p");
		for (int i = 0; i < tagP.size(); i++) {
			Element element = tagP.get(i);
			if (element != null) {
				ProvinceCode provinceCode = new ProvinceCode(i);
				Element first = element.select(">span").first();
				Element last = element.select(">span").last();
				String code = StringUtils.trim(first.text());
				String name = StringUtils.trim(last.text());
				provinceCode.setCode(code);
				provinceCode.setName(name);
				pList.add(provinceCode);
			}
		}
		String json = new Gson().toJson(pList);
		File file = new File("C://p.json");
		if(!file.exists()){
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		byte[] bytes = json.getBytes();
		BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(bytes));
		int read;
		while ((read = inputStream.read()) != -1) {
			fos.write(read);
		}
		fos.close();
	}
}
